//
//  HWTabBarController.swift
//  HWanGame
//
//  Created by 王昌健 on 2021/12/29.
//  Copyright © 2021 94Wan. All rights reserved.
//

import UIKit

class HWTabBarController1: CYLTabBarController {
    
    private let lottieNameArr: [String] = ["home", "info", "square", "welfare", "mine"]
    var animationView: LOTAnimationView?
    private lazy var tabBarSwappableImageViews: [UIImageView] = {
        //        2.遍历取出所有的 tabBarButton
        var tempArray = [UIImageView]()
        for tempView in self.tabBar.subviews where tempView.isKind(of: NSClassFromString("UITabBarButton")!) {

            for tempImgV in tempView.subviews {
                //2.1 继续遍历tabBarButton 找到 UITabBarSwappableImageView 并保存
                //第一种层级关系 UITabBarButton --> UITabBarSwappableImageView
                if tempImgV.isKind(of: NSClassFromString("UITabBarSwappableImageView")!) {

                    tempArray.append(tempImgV as! UIImageView)
                }
            }
        }
        return tempArray
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.delegate = self
        //tabbar背景色
        UITabBar.appearance().backgroundColor = "#F7F8FA".toColor
        
        //tabbar字体颜色
        //        UITabBar.appearance().tintColor = .colorWithHexString(hexString: "#888888")
        //        UITabBar.appearance().unselectedItemTintColor = .colorWithHexString(hexString: "#888888")
        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.colorWithHexString(hexString: "#F87706"), NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 12)], for: .selected)
        // 修改标签栏未选中时文字颜色、字体
        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.colorWithHexString(hexString: "#888888"), NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 12)], for: .normal)
        UITabBar.appearance().isTranslucent = false
        self.delegate = self
        UITabBar.appearance().backgroundImage = UIImage()
        //        UITabBar.appearance().layer.shadowColor = UIColor.red.cgColor
        //        UITabBar.appearance().layer.shadowOffset = CGSize(width: 0, height: -3)
        tabBar.layer.shadowColor = UIColor.colorWithAlphaHexString(hexString: "#C4C4C4", alpha: 0.16).cgColor
        tabBar.layer.shadowOffset = CGSize(width: 0, height: -3)
        tabBar.layer.shadowOpacity = 1
        tabBar.layer.shadowRadius = 6
        tabBar.layer.shadowPath = UIBezierPath(rect: tabBar.bounds).cgPath
        
        
        
        if #available(iOS 15.0, *)  {
            let appearance = UITabBarAppearance()
            appearance.configureWithOpaqueBackground()
            appearance.backgroundImage = UIImage()
            appearance.shadowImage = UIColor.createImageWithColor(color: .white)
            appearance.stackedLayoutAppearance.normal.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.colorWithHexString(hexString: "#888888"), NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 12)]
            appearance.stackedLayoutAppearance.selected.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.colorWithHexString(hexString: "#F87706"), NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 12)]
            
            appearance.inlineLayoutAppearance.normal.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.colorWithHexString(hexString: "#888888"), NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 12)]
            appearance.inlineLayoutAppearance.selected.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.colorWithHexString(hexString: "#F87706"), NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 12)]
            
            appearance.compactInlineLayoutAppearance.normal.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.colorWithHexString(hexString: "#888888"), NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 12)]
            appearance.compactInlineLayoutAppearance.selected.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.colorWithHexString(hexString: "#F87706"), NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 12)]
            UITabBar.appearance().standardAppearance = appearance
            UITabBar.appearance().scrollEdgeAppearance = appearance
            
            UITabBar.appearance().tintColor = UIColor.colorWithHexString(hexString: "#F87706")
            UITabBar.appearance().layer.shadowColor = UIColor.colorWithAlphaHexString(hexString: "#C4C4C4", alpha: 0.16).cgColor
            UITabBar.appearance().layer.shadowOffset = CGSize(width: 0, height: -3)
            UITabBar.appearance().layer.shadowOpacity = 1
            UITabBar.appearance().layer.shadowRadius = 6
            
            //            UITabBar.appearance().shadowImage = UIImage()
            //            UITabBar.appearance().backgroundImage = UIImage()
            //            UITabBar.appearance().layer.shadowPath = UIBezierPath(rect: tabBar.bounds).cgPath
        }
        
        
//                UITabBar.appearance().backgroundImage = scanImage(image: UIImage(named: "tab1")!, scan: Float(widthScale))
//        UITabBar.appearance().backgroundImage = UIImage(named: "tab1")
        //        UITabBar.appearance().backgroundColor = .clear
        
        //        if let myTabbar = tabBar as? HWTabBar {
        //            myTabbar.centerButtonActionHandler = {
        //                print("Center Button Tapped")
        //                self.selectedIndex = 2
        //            }
        //        }
        //
        //        let home = HWNavigationViewController(rootViewController: HWHomeViewController())
        //        let game = HWNavigationViewController(rootViewController: HWGameClassificationViewController())
        //        //        let video = HWNavigationViewController(rootViewController: HWVideoshipingViewController())
        //        let fuli = HWFulijiemiamanViewController()
        //        fuli.title = "福利"
        //        let fuliNav = HWNavigationViewController(rootViewController: fuli)
        //        let mine = HWNavigationViewController(rootViewController: HWMineViewController())
        //
        //        addControllerView(titlleStr: "首页", imageName: "home_Normal", selectImage: "home_Normal", controller: HWHomeViewController())
        //        addControllerView(titlleStr: "首页", imageName: "home_Normal", selectImage: "home_Normal", controller: HWHomeViewController())
        //        addControllerView(titlleStr: "首页", imageName: "home_Normal", selectImage: "home_Normal", controller: HWHomeViewController())
        //        addControllerView(titlleStr: "首页", imageName: "home_Normal", selectImage: "home_Normal", controller: HWHomeViewController())
//        UITabBar.appearance().barTintColor = .colorWithHexString(hexString: "#F7F7F7")
        
//        let bgImageView = UIImageView()
//        bgImageView.backgroundColor = .colorWithHexString(hexString: "#F7F7F7")
//        bgImageView.image = UIImage(named: "tabbarBg")
////        bgImageView.contentMode = .scaleAspectFill
//        bgImageView.frame = CGRect(x: 0, y: -10, width: screenWidth, height: 73*widthScale)
//        UITabBar.appearance().insertSubview(bgImageView, at: 0)
        
    }
    
}

extension HWTabBarController1 {
    
    override func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        self.updateSelectionStatusIfNeeded(for: tabBarController, shouldSelect: viewController)
        return true
    }
    
        func scanImage(image:UIImage,scan:Float) -> UIImage {
            let image1 = image.resizableImage(withCapInsets: UIEdgeInsets(top: 0, left: 10, bottom: 10, right: 10), resizingMode: .stretch)
            UIGraphicsBeginImageContext(CGSize(width: screenWidth, height: 68))
            image1.draw(in: CGRect(x: 0, y: 0, width: screenWidth, height: 68))
    
            let scaledImage = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
            UIGraphicsEndImageContext()
            return scaledImage
        }
    ///
    
    //    func addControllerView(titlleStr : String, imageName: String ,selectImage :String , controller :UIViewController)  {
    //
    //
    //        controller.tabBarItem.image = UIImage(named: imageName);
    //        // controller.tabBarItem.title = title;
    //        let seletimage =    UIImage(named: selectImage)
    //        controller.tabBarItem.selectedImage =  seletimage?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal);
    //        controller.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.colorWithHexString(hexString: "#999999") ], for: UIControl.State.normal)
    //        controller.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.colorWithHexString(hexString: "#3AA9AF") ], for: UIControl.State.selected)
    //        controller.tabBarItem.title = titlleStr
    //        let   nav =  HWNavigationController(rootViewController: controller)
    //        addChild(nav);
    //
    //    }
}

//MARK: 动画
extension HWTabBarController1 {
    
    override func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
//        super.tabBarController(tabBarController, didSelect: viewController)
        setupAnimation(tabBarController, viewController)
    }
    
    // 隐藏所有选项卡的文字
//    func hideTabBarItemsText() {
//
//        if selectedIndex == 0 {
//            tabBar.selectedItem?.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.clear], for: .normal)
//        }
//    }
    
    private func getAnimationViewAtTabBarIndex(_ index: Int, _ frame: CGRect)-> LOTAnimationView{
        
        let view = LOTAnimationView(name: lottieNameArr[index])
        view.frame = frame
        view.contentMode = .scaleAspectFill
        view.animationSpeed = 1
        return view
    }

    private func setupAnimation(_ tabBarVC: UITabBarController, _ viewController: UIViewController){

        if animationView != nil {
            animationView!.stop()
            animationView?.removeFromSuperview()
        }

    //        1. 获取当前点击的是第几个
        let index = tabBarVC.viewControllers?.firstIndex(of: viewController)
//        3. 找到当前的UITabBarButton
        let currentTabBarSwappableImageView = tabBarSwappableImageViews[index!]

//        4. 获取UITabBarButton中的 UITabBarSwappableImageView 并隐藏
        var frame = currentTabBarSwappableImageView.frame
        frame.origin.x = 0
        frame.origin.y = 0
        frame.size.width = 36
        frame.size.height = 36
        let animation: LOTAnimationView? = getAnimationViewAtTabBarIndex(index!, frame)
        self.animationView = animation
         self.animationView!.center = currentTabBarSwappableImageView.center
    //        5. 创建动画 view 加载到 当前的 UITabBarButton 并隐藏 UITabBarSwappableImageView
        currentTabBarSwappableImageView.superview?.addSubview( animation!)
        currentTabBarSwappableImageView.isHidden = true
        
        animation?.loopAnimation = false
        animation?.play(){ finish in
            animation?.removeFromSuperview()
            self.animationView?.removeFromSuperview()
            currentTabBarSwappableImageView.isHidden = false
        }
        
    }
    
    
}
